#region Using

using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;

using Gizmox.WebGUI.Forms;
using System.IO;
#endregion

namespace TVC.Forms
{
    public partial class frmMulticlsTransferIn : Form
    {
        string fileType = "";
        private readonly DataSet ds = new DataSet();
        readonly Dictionary<string, object> arrParam = new Dictionary<string, object>();
        public MainForm MainForm { set; get; }
        public frmMulticlsTransferIn(string args, MainForm form)
        {
            InitializeComponent();
            InitCommand(args);
            MainForm = form;
        }
        public frmMulticlsTransferIn(Gizmox.WebGUI.Common.Interfaces.IContext objContext)
            : base(objContext)
        {

        }
        public frmMulticlsTransferIn(MainForm form)
        {
            MainForm = form;
        }


        private void InitCommand(string args)
        {
            string[] arr = args.Split('&');
            if (arr != null)
                foreach (string it in arr)
                {
                    string[] value = it.Split('=');
                    if (value != null && value.Length == 2)
                    {
                        arrParam.Add(value[0], value[1]);
                    }
                }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            ofd.FileOk += (form, args) =>
            {
                if (((OpenFileDialog)form).DialogResult == Gizmox.WebGUI.Forms.DialogResult.OK)
                {
                    txtFileName.Text = ofd.FileName;
                    fileType = Path.GetExtension(ofd.File.OriginalFileName);
                    btnPreview.Enabled = true;
                    btnGroup.Enabled = btnImport.Enabled = false;
                }
            };
            ofd.ShowDialog();

        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            string sErr = "";
            lblErr.Text = "";
            ds.Tables.Clear();
            if (arrParam.ContainsKey("src"))
            {
                string[] arrType = arrParam["src"].ToString().Split(',');
                foreach (string type in arrType)
                {
                    DataTable dt = MainForm.GetTableStruct(type);
                    dt.TableName = type;
                    dt = clsTransfer.PreviewExcelFile(dt, txtFileName.Text, "", type);
                    sErr = MainForm.TVCFormatData(dt, sErr, type);
                    ds.Tables.Add(dt);
                    foreach (DataRow row in dt.Rows)
                    {
                        if (dt.Columns.Contains("DTB"))
                            row["DTB"] = MainForm.DB;
                        if (dt.Columns.Contains("DB"))
                            row["DB"] = MainForm.DB;
                        if (dt.Columns.Contains("CreatedBy"))
                        {
                            row["ModifiedBy"] = MainForm.PODInfo.USER_ID;
                            row["CreatedBy"] = MainForm.PODInfo.USER_ID;
                            row["ModifiedDate"] = DateTime.Now;
                            row["CreatedDate"] = DateTime.Now;
                        }
                        
                    }
                }
                ShowDataSet();
            }
            if (lblErr.Text.Trim() == "")
            {
                lblErr.Text = lblErr.Text.Trim();
                btnGroup.Enabled = true;
                btnPreview.Enabled = false;
            }
        }

        private void ShowDataSet()
        {
            tabMain.TabPages.Clear();
            foreach (DataTable dt in ds.Tables)
            {
                TabPage tb = new TabPage(dt.TableName);
                tabMain.TabPages.Add(tb);
                DataGridView dgv = new DataGridView() { Name = dt.TableName, Dock = DockStyle.Fill, DataSource = dt };
                if (dt.ExtendedProperties.ContainsKey("Caption"))
                    dgv.Text = dt.ExtendedProperties["Caption"].ToString();
                else dgv.Text = dt.TableName;
                dgv.Text += " - RowCount: " + dt.Rows.Count;
                //tb.Text = dgv.Text;
                dgv.DataError += dgvList_DataError;
                dgv.RowHeaderMouseClick += dgv_RowHeaderMouseClick;
                //dgv.RowHeadersVisible = false;
                dgv.RowHeadersWidth = 25;
                dgv.ReadOnly = true;
                dgv.AllowUserToAddRows = false;
                dgv.IsCaptionVisible = true;
                tb.Controls.Add(dgv);
                clsTransfer clsTransfer = new clsTransfer(MainForm);
                clsTransfer.ValidateDGV(dgv, errorProvider1);
                lblErr.Text += String.Format("{0}\n", errorProvider1.GetError(dgv));
            }
        }

        void dgv_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView dgvList = sender as DataGridView;
            if (dgvList != null)
                if (e.RowIndex != -1)
                    if (dgvList.Rows[e.RowIndex].ErrorText != "")
                        lblErr.Text = dgvList.Rows[e.RowIndex].ErrorText;
        }

        private void btnImport_Click(object sender, EventArgs e)
        {

            string sErr = "";
            if (ckbIns.Checked == false && ckbUp.Checked == false)
            {
                MessageBox.Show("Please select a mode!");
                return;
            }
            btnImport.Enabled = false;
            foreach (DataTable dt in ds.Tables)
            {
                Control[] control = Controls.Find(dt.TableName, true);
                if (control != null && control.Length == 1)
                {
                    
                    DataGridView dgvList = control[0] as DataGridView;
                    for (int i = 0; i < dgvList.Rows.Count; i++)
                    {
                        if (dgvList.Rows[i].ErrorText == "")
                        {
                            sErr += BUS.CommonControl.TransferInData(((DataRowView)dgvList.Rows[i].DataBoundItem).Row, dt.TableName,MainForm.PODInfo);
                        }
                    }
                }
            }
            if (sErr == "")
                Close();
            lblErr.Text = sErr;
        }

        private void dgvList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            DataGridView dgvList = sender as DataGridView;
            if (dgvList != null)
            {
                dgvList.Rows[e.RowIndex].ErrorText = e.ThrowException.ToString();
                dgvList.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
                lblErr.Text += String.Format("{0}\n", e.ThrowException);
                errorProvider1.SetError(dgvList, lblErr.Text);
            }
        }

        private void btnGroup_Click(object sender, EventArgs e)
        {
            btnGroup.Enabled = false;
            btnImport.Enabled = true;


            foreach (TabPage tb in tabMain.TabPages)
            {
                if (tb.Controls.Count == 1)
                {
                    DataGridView dgv = tb.Controls[0] as DataGridView;
                    if (dgv != null)
                    {
                        DataSet dset = new DataSet();
                        DataTable dt = dgv.DataSource as DataTable;
                        DataSetHelper dsHelper = new DataSetHelper(ref dset);
                        string strField = "";
                        string filter = "";
                        string groupField = "";
                        foreach (DataColumn col in dt.Columns)
                        {
                            strField += "," + col.ColumnName;
                            groupField += "," + col.ColumnName;
                        }
                        strField = strField.Substring(1);
                        groupField = groupField.Substring(1);

                        DataTable dtgroup = dsHelper.SelectGroupByInto("Group", dt, strField, filter, groupField);
                        string caption = "";
                        if (dt.ExtendedProperties.ContainsKey("Caption"))
                            caption = dt.ExtendedProperties["Caption"].ToString();
                        else caption = dt.TableName;

                        dt = dtgroup.Copy();
                        dt.ExtendedProperties.Add("Caption", caption);
                        dgv.DataSource = dt;
                        dgv.Text = String.Format("{0} - RowCount: {1}", caption, dt.Rows.Count);

                    }
                }
            }
        }


    }
}